/**
 * 
 */
package net.bingosoft.common.upload;

import java.security.SecureRandom;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

/**
 * IUploadPolicy的缺省实现
 * @author elvis
 */
public class UploadPolicy implements IUploadPolicy {
    
    private static SecureRandom rnd = new SecureRandom();

    /* (non-Javadoc)
     * @see bingo.form.upload.IUploadPolicy#generateServerName(bingo.form.upload.UploadConfig, bingo.form.upload.UploadFile, javax.servlet.http.HttpServletRequest)
     */
    public String generateServerName(UploadConfig config, UploadFile file, HttpServletRequest request) {
        //按当前时间的分钟毫秒+3位随机数
        Calendar c = Calendar.getInstance();
        String min  = get(c,Calendar.MINUTE);
        String sec  = get(c,Calendar.SECOND);
        String mis  = get(c,Calendar.MILLISECOND);
        String rnd  = random();
        String ext  = getFileExt(file.getClientName());
        
        return min + sec + mis + rnd + ext;
    }

    /* (non-Javadoc)
     * @see bingo.form.upload.IUploadPolicy#generateServerPath(bingo.form.upload.UploadConfig, bingo.form.upload.UploadFile, javax.servlet.http.HttpServletRequest)
     */
    public String generateServerFolder(UploadConfig config, UploadFile file, HttpServletRequest request) {
        //按当前年月日和小时生成文件路径
        Calendar c  = Calendar.getInstance();
        String year = get(c,Calendar.YEAR);
        String mon  = get(c,Calendar.MONTH);
        String day  = get(c,Calendar.DAY_OF_MONTH);
        String hour = get(c,Calendar.HOUR_OF_DAY);
        
        return year + "/" + mon + "/" + day + "/" + hour + "/";
    }

    private static String get(Calendar c,int field){
        int v = c.get(field);
        if(field == Calendar.MONTH){
            v += 1;
        }
        String value = String.valueOf(v);
        if(value.length() == 1){
            value = "0" + value;
        }
        return value;
    }
    
    private static String getFileExt(String fileName){
        if(null != fileName){
            int dot = fileName.lastIndexOf(".");
            if(dot >= 0){
                return fileName.substring(dot);
            }
        }
        return "";
    }
    
    private static String random(){
        String value = String.valueOf(rnd.nextInt(1000));
        if(value.length() < 3){
            for(int i=value.length();i<3;i++){
                value = "0" + value;
            }
        }
        return value;
    }
}
